use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use anyhow::Result;
use salvo::Depot;
use tracing::info;

use crate::config::app_error::{AppError, AppResult};
use crate::di::services::{DatabaseService, ConfigService, ExtensionStoreService};
use crate::services::role_di::RoleServiceDI;
use crate::extension::model::user::{
    CreateUserRequest, DetailedUser, LoginUserInfo, User, UserPermission,
    AVATAR_ATTACHMENT_NAME_ANNO, EMAIL_TO_VERIFY, LAST_AVATAR_ATTACHMENT_NAME_ANNO,
    ROLE_NAMES_ANNO,
};
use crate::extension::model::role::Role;
use crate::extension::model::role_binding::{RoleBinding, Subject};
use crate::extension::model::{role, role_binding};
use crate::utils::{rand_utils, user_util};
use halo_model::ExtensionOperator;

/// 使用依赖注入的用户服务实现
/// 
/// 这个服务不依赖全局状态，而是通过构造函数注入所需的依赖
pub struct UserServiceDI {
    store_service: Arc<ExtensionStoreService>,
    role_service: Arc<RoleServiceDI>,
    config_service: Arc<ConfigService>,
}

impl UserServiceDI {
    /// 创建新的用户服务实例
    pub fn new(
        store_service: Arc<ExtensionStoreService>,
        role_service: Arc<RoleServiceDI>,
        config_service: Arc<ConfigService>,
    ) -> Self {
        Self {
            store_service,
            role_service,
            config_service,
        }
    }

    /// 获取当前用户信息
    pub async fn me(&self, depot: &mut Depot) -> AppResult<DetailedUser> {
        let username = user_util::current_username(depot);
        info!("current_user: {}", username);
        
        // 这里需要实现从store_service获取用户的逻辑
        // 暂时返回一个示例实现
        let user = self.get_user_by_name(username).await?;
        self.to_detail_user(user).await
    }

    /// 根据用户名获取用户
    pub async fn get_user_by_name(&self, name: String) -> AppResult<User> {
        // 这里需要实现从store_service获取用户的逻辑
        // 暂时返回一个错误，实际实现需要调用store_service
        Err(anyhow::anyhow!("User service implementation pending").into())
    }

    /// 将用户转换为详细用户信息
    pub async fn to_detail_user(&self, user: User) -> AppResult<DetailedUser> {
        let metadata = user.get_metadata().clone();
        let annotations = metadata.get_annotations();
        let role_names_json = annotations.map_or_else(|| None, |a| a.get(ROLE_NAMES_ANNO).cloned());

        let role_name_list: Vec<String> = match role_names_json {
            Some(s) => serde_json::from_str(&s)?,
            None => Vec::new(),
        };

        // 这里需要通过role_service获取角色列表
        // 暂时返回空列表
        let role_list = Vec::new();

        Ok(DetailedUser {
            user,
            roles: role_list,
        })
    }

    /// 创建用户
    pub async fn create_user(&self, create_user_request: CreateUserRequest) -> AppResult<User> {
        if create_user_request.name.trim().is_empty() {
            return Err(anyhow::anyhow!("Name is required").into());
        }

        if create_user_request.email.trim().is_empty() {
            return Err(anyhow::anyhow!("Email is required").into());
        }

        let user = create_user_request.to_user();
        let role_names = create_user_request.roles.unwrap_or_default();
        
        // 这里需要实现用户创建逻辑
        // 暂时返回错误
        Err(anyhow::anyhow!("Create user implementation pending").into())
    }

    /// 更新用户密码
    pub async fn update_with_raw_password(&self, username: String, raw_password: String) -> AppResult<()> {
        // 这里需要实现密码更新逻辑
        // 暂时返回错误
        Err(anyhow::anyhow!("Update password implementation pending").into())
    }

    /// 授予角色
    pub async fn grant_roles(&self, username: String, roles: &HashSet<String>) -> AppResult<User> {
        // 这里需要实现角色授予逻辑
        // 暂时返回错误
        Err(anyhow::anyhow!("Grant roles implementation pending").into())
    }

    /// 获取用户权限
    pub async fn get_user_permission(&self, name: String, depot: &mut Depot) -> AppResult<UserPermission> {
        let username = depot
            .obtain::<Arc<LoginUserInfo>>()
            .map(|u| u.username.clone())
            .unwrap_or_default();

        // 这里需要实现权限获取逻辑
        // 暂时返回空权限
        Ok(UserPermission {
            roles: HashSet::new(),
            permissions: Vec::new(),
            ui_permissions: HashSet::new(),
        })
    }

    /// 列出用户角色
    pub async fn list_roles(&self, username: String) -> AppResult<Vec<Role>> {
        // 这里需要实现角色列表获取逻辑
        // 暂时返回空列表
        Ok(Vec::new())
    }

    /// 更新用户资料
    pub async fn update_profile(&self, depot: &mut Depot, user: User) -> AppResult<User> {
        let current_user_name = user_util::current_username(depot);
        let username = user.get_metadata().get_name();
        
        if current_user_name != username {
            return Err(anyhow::anyhow!("Username didn't match.").into());
        }

        // 这里需要实现用户资料更新逻辑
        // 暂时返回错误
        Err(anyhow::anyhow!("Update profile implementation pending").into())
    }
}

/// 用户服务工厂函数
/// 
/// 用于在依赖注入容器中创建UserServiceDI实例
pub fn create_user_service_di(
    store_service: Arc<ExtensionStoreService>,
    role_service: Arc<RoleServiceDI>,
    config_service: Arc<ConfigService>,
) -> Result<UserServiceDI> {
    Ok(UserServiceDI::new(store_service, role_service, config_service))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::di::ServiceContainer;
    use crate::config::{Configs, Server, DataBase, Log, Jwt, Cert};

    fn create_test_config() -> Configs {
        Configs {
            server: Server {
                name: "test".to_string(),
                address: "127.0.0.1:8080".to_string(),
                ssl: false,
            },
            database: DataBase {
                database_url: "sqlite::memory:".to_string(),
            },
            log: Log {
                filter_level: "info".to_string(),
                with_ansi: true,
                to_stdout: true,
                directory: "./logs".to_string(),
                file_name: "test.log".to_string(),
                rolling: "daily".to_string(),
            },
            jwt: Jwt {
                jwt_secret: "test_secret".to_string(),
                jwt_exp: 3600,
            },
            cert: Cert {
                cert: "test.pem".to_string(),
                key: "test.key".to_string(),
            },
        }
    }

    #[tokio::test]
    async fn test_user_service_creation() {
        let container = ServiceContainer::new();
        let config = create_test_config();
        
        // 注册配置服务
        container.register_singleton::<ConfigService, _>(move |_| {
            Ok(ConfigService::new(config.clone()))
        }).unwrap();

        // 测试配置服务解析
        let config_service = container.resolve::<ConfigService>().unwrap();
        assert_eq!(config_service.config().server.name, "test");
    }

    #[tokio::test]
    async fn test_user_service_dependencies() {
        // 这里可以测试用户服务的依赖注入
        // 由于需要数据库连接，暂时跳过实际的数据库操作测试
    }
}
